use super::db;
use super::request::TaskInfo;
use super::response::TaskInfoRes;

// 获取 任务详情
pub async fn get_task_detail(id: u64) -> Result<Vec<TaskInfoRes>, sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let query = "SELECT * FROM tb_task WHERE module_id = ?";
    let resp = sqlx::query_as::<_, TaskInfoRes>(query)
        .bind(id)
        .fetch_all(pool)
        .await?;
    Ok(resp)
}

// 新增 task
pub async fn add_task(modules_id: u64, data: TaskInfo) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let query = "INSERT INTO tb_task (module_id, core, task_name, gpio, device, topic,created_at, updated_at) VALUES (?,?,?,?,?,?, NOW(), NOW())";
    let res = sqlx::query(query)
        .bind(modules_id)
        .bind(data.core)
        .bind(data.task_name)
        .bind(data.gpio)
        .bind(data.device)
        .bind(data.topic)
        .execute(pool)
        .await?;
    Ok(())
}

// 编辑 task
pub async fn edit_task(data: TaskInfo) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let query = "UPDATE tb_task SET core = ?, device = ?, topic = ?, gpio = ?, task_name = ?, updated_at = NOW() WHERE id = ?";
    let res = sqlx::query(query)
        .bind(data.core)
        .bind(data.device)
        .bind(data.topic)
        .bind(data.gpio)
        .bind(data.task_name)
        .bind(data.id)
        .execute(pool)
        .await?;
    Ok(())
}

// 删除 task
pub async fn delete_task(id: u64) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let _res = sqlx::query("DELETE FROM tb_task WHERE id=?")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(())
}
